package api

import (
	"My_Blog02/model"
	"My_Blog02/utils/errmsg"
	"github.com/gin-gonic/gin"
	"strconv"
)

// 增加文章
func AddArticle(c *gin.Context) {
	var article model.Article
	err := c.ShouldBindJSON(&article)
	if err != nil {
		c.JSON(200, gin.H{
			"status": 200,
			"msg":    errmsg.GetMsg(500),
			"data":   nil,
		})
	}
	returnArticle, code := model.Add_Article(&article)
	c.JSON(200, gin.H{
		"status": 200,
		"data":   returnArticle,
		"msg":    errmsg.GetMsg(code),
	})
}

// 删除文章
func DeleteArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(200, gin.H{
			"status": 200,
			"msg":    errmsg.GetMsg(errmsg.ERROR),
			"data":   nil,
		})
	}
	return_Article, code := model.Delete_Article(id)
	c.JSON(200, gin.H{
		"status": 200,
		"data":   return_Article,
		"msg":    errmsg.GetMsg(code),
	})
}

// 修改文章
func ModifyArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(200, gin.H{
			"status": 200,
			"msg":    errmsg.GetMsg(errmsg.ERROR),
			"data":   nil,
		})
	}
	var article model.Article
	err = c.ShouldBindJSON(&article)
	article.ID = uint(id)
	if err != nil {
		c.JSON(200, gin.H{
			"status": 200,
			"msg":    errmsg.GetMsg(errmsg.ERROR),
			"data":   nil,
		})
	}

	returnArticle, code := model.Modify_Article(id, article)
	c.JSON(200, gin.H{
		"status": 200,
		"data":   returnArticle,
		"msg":    errmsg.GetMsg(code),
	})

}

// 查询文章
func SearchArticle(c *gin.Context) {
	id, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		c.JSON(200, gin.H{
			"status": 200,
			"msg":    errmsg.GetMsg(errmsg.ERROR),
			"data":   nil,
		})
	}
	article, code := model.Search_Article(id)
	c.JSON(200, gin.H{
		"status": 200,
		"data":   article,
		"msg":    errmsg.GetMsg(code),
	})
}
